package com.ldc.security.handle;

import com.ldc.common.constants.ConstantsParams;
import com.ldc.common.utils.JwtTokenUtils;
import com.ldc.common.utils.ResponseUtils;
import com.ldc.model.utils.ResultUtils;
import com.ldc.security.model.LoginUserBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 登录成功
 *
 * @auther liudc
 * @since 2022/11/6
 */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private final Logger logger = LoggerFactory.getLogger(CustomAuthenticationSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 获取登录的主体
        final LoginUserBean userBean = (LoginUserBean) authentication.getPrincipal();
        if (null == userBean) {
            ResponseUtils.toResult(response, ResultUtils.toFailed("身份验证 失败~"));
            return;
        }
        logger.info("用户名 {}", userBean.getUsername());
        Map<String, Object> data = new HashMap<>();
        data.put(ConstantsParams.TOKEN, createToken(userBean));
        // 封装数据
        ResponseUtils.toResult(response, ResultUtils.toLoginSuccess(data));
    }


    /**
     * 获取授权信息
     *
     * @param userBean 授权信息
     * @return 数据 map
     */
    private String createToken(LoginUserBean userBean) {
        Map<String, Object> map = new HashMap<>();
        map.put(ConstantsParams.USER_NAME, userBean.getUsername());
        map.put(ConstantsParams.USER_ID, userBean.getUserBean().getId());
        map.put(ConstantsParams.ROLES, getRoles(userBean.getAuthorities()));
        return JwtTokenUtils.createToken(map);
    }

    /**
     * 获取角色信息
     *
     * @param grantedAuthorities 授予的权限
     * @return 角色
     */
    private String getRoles(List<GrantedAuthority> grantedAuthorities) {
        if (null == grantedAuthorities || grantedAuthorities.size() == 0) {
            return "";
        }
        return grantedAuthorities
                .stream().map(GrantedAuthority::getAuthority)
                .collect(Collectors.joining(","));

    }

}
